package com.kobeliu.api.mq;


import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * rabbitMQ工具类
 */
@Configuration
@Slf4j
public class RabbitMQSMSConfig {

    //定义交换机名称
    public static final String SMS_EXCHANGE = "sms_exchange";
    public static final String SMS_QUEUE = "sms_queue";

    //定义固定的routingKey
    public static final String ROUTING_KEY_SMS_SEND_LOGIN = "imooc.sms.send.login";

    //创建交换机
    @Bean(SMS_EXCHANGE)
    public Exchange exchange(){
        return ExchangeBuilder.topicExchange(SMS_EXCHANGE).durable(true).build();
    }

    //创建队列
    @Bean(SMS_QUEUE)
    public Queue queue(){
        return QueueBuilder.durable(SMS_QUEUE)
                .withArgument("x-message-ttl",10*1000)
                .build();
    }

    //创建绑定关系
    @Bean
    public Binding smsBinding(@Qualifier(SMS_EXCHANGE) Exchange exchange, @Qualifier(SMS_QUEUE) Queue queue){
        return BindingBuilder.bind(queue)
                            .to(exchange)
                            .with("imooc.sms.#")
                            .noargs();
    }

    @Bean
    public RabbitTemplate.ConfirmCallback confirmCallback() {
        RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
            /**
             * 回调函数
             *
             * @param correlationData 传入的数据
             * @param ack             true为成功 false为失败
             * @param msg             若成功，传回null,若失败，传回原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String msg) {

                log.info("传入交换机的消息为:{}", correlationData);
                log.info("传入是否成功:{}", ack);
                log.info("若传入失败，原因是:{}", msg);

            }

        };
        return confirmCallback;
    }

}
